﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace Stone.Web
{
    public class Global : System.Web.HttpApplication
    {
        public Stone.Services.Application ApplicationInstance
        {
            get { return Stone.Services.Application.Instance; }
        }

        public bool Startup()
        {
            if (ApplicationInstance.Start())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool Shutdown()
        {
            return ApplicationInstance.Stop();
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            Startup();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (ApplicationInstance.Status != Stone.Services.ApplicationStatus.Started)
            {
                if (ApplicationInstance.LastException == null)
                {
                    Response.Write("应用程序已停止运行!");
                    Response.End();
                }
                else
                {
                    //是因为异常没有启动，重新尝试~
                    if (!Startup())
                    {
                        try
                        {
                            Response.Write("<h1>系统启动时发生异常:" + ApplicationInstance.LastException.Message + "</h1><br/>");
                            Response.Write("<b>详细:</b>" + (ApplicationInstance.LastException.ToString() ?? "无").Replace(Environment.NewLine, "<br/>"));
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.ToString().Replace(Environment.NewLine, "<br/>"));
                        }
                        Response.End();
                    }
                }
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            Shutdown();
        }
    }
}